const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')
const { resolve } = require('path')
const { copyFileSync, mkdirSync, existsSync, rmSync } = require('fs')

// 清理dist目录
if (existsSync('dist')) {
  rmSync('dist', { recursive: true })
}

// 运行vite构建
execSync('vite build', { stdio: 'inherit' })

// 递归查找HTML文件
function findHtmlFile(dir) {
  const files = fs.readdirSync(dir)
  for (const file of files) {
    const filePath = path.join(dir, file)
    const stat = fs.statSync(filePath)
    if (stat.isDirectory()) {
      const found = findHtmlFile(filePath)
      if (found) return found
    } else if (file.endsWith('.html')) {
      return filePath
    }
  }
  return null
}

// 查找并重命名HTML文件
const distDir = path.join(__dirname, '../dist')
const htmlFile = findHtmlFile(distDir)

if (htmlFile) {
  fs.renameSync(
    htmlFile,
    path.join(distDir, 'popup.html')
  )
} else {
  console.error('未找到HTML文件')
  process.exit(1)
}

// 复制content script
copyFileSync(
  resolve(__dirname, '../src/content/content.js'),
  resolve(__dirname, '../dist/content.js')
)

// 复制background script
copyFileSync(
  resolve(__dirname, '../src/background/background.js'),
  resolve(__dirname, '../dist/background.js')
)

// 复制manifest和图标
const copyAssets = require('./copy-assets')

console.log('构建完成!') 